<template>
  <el-card class="change-password-card">
    <div slot="header">
      <h2>修改密码</h2>
    </div>
    <el-form
      ref="passwordForm"
      :model="passwordForm"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
          type="password"
          v-model="passwordForm.currentPassword"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="passwordForm.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="passwordForm.confirmPassword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" icon="el-icon-check"
          >确认修改
        </el-button>
        <el-button @click="handleCancel" icon="el-icon-back">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
  export default {
    data() {
      const validateConfirmPassword = (rule, value, callback) => {
        if (value !== this.passwordForm.newPassword) {
          callback(new Error("两次输入的新密码不一致"));
        } else {
          callback();
        }
      };

      return {
        passwordForm: {
          currentPassword: "",
          newPassword: "",
          confirmPassword: "",
        },
        userId: null,
        rules: {
          currentPassword: [
            { required: true, message: "请输入当前密码", trigger: "blur" },
          ],
          newPassword: [
            { required: true, message: "请输入新密码", trigger: "blur" },
            { min: 6, message: "新密码长度不能少于 6 个字符", trigger: "blur" },
          ],
          confirmPassword: [
            { required: true, message: "请确认新密码", trigger: "blur" },
            { validator: validateConfirmPassword, trigger: "blur" },
          ],
        },
      };
    },
    created() {
      const user = JSON.parse(localStorage.getItem("user") || "{}");
      this.userId = user.id;
    },
    methods: {
      async handleSubmit() {
        this.$refs.passwordForm.validate(async (valid) => {
          if (valid) {
            try {
              await this.$axios.put("/auth/change-password", {
                current_password: this.passwordForm.currentPassword,
                new_password: this.passwordForm.newPassword,
              });

              this.$message.success("密码修改成功，请重新登录");

              // 清除本地存储并跳转到登录页
              this.$store.dispatch("logout");
              // localStorage.removeItem("token");
              // localStorage.removeItem("user");
              this.$router.push("/auth/login");
            } catch (error) {
              this.$message.error(error?.data?.message || "密码修改失败");
              console.error(error);
            }
          } else {
            return false;
          }
        });
      },
      handleCancel() {
        this.$router.go(-1);
      },
    },
  };
</script>

<style scoped>
  .change-password-card {
    max-width: 600px;
    margin: 20px auto;
  }
</style>
